package com.xbw.bookSale.dao;

import java.sql.*;

public class BaseDAO {

	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	protected Connection conn = null;
	protected ResultSet rs = null;
	protected Statement stmt = null;

	public BaseDAO() {
		try {
			conn = DriverManager
					.getConnection(
							"jdbc:mysql://localhost:3306/bookSale?useUnicode=true&characterEncoding=UTF-8",
							"root", "root");
			// System.out.println(conn.isClosed());
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public ResultSet query(String sql) {
		try {
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}

	public int executeSQL(String sql) {
		try {
			Statement stmt = conn.createStatement();
			int row = stmt.executeUpdate(sql);
			return row;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}

	public void close() {

		if (stmt != null) {
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			stmt = null;
		}

		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			rs = null;
		}

		try {
			if (conn != null && !conn.isClosed()) {
				conn.close();
				conn = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

}
